package com.example.service.impl;

import com.example.mapper.LoginMapper;
import com.example.pojo.ChangePassword;
import com.example.pojo.Result;
import com.example.pojo.Student;
import com.example.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;
    @Override
    public Student login(Student student) {
        log.info("登录 --->>>  学号：{}，密码：{}",student.getStudentID(),student.getPassword());
        student = loginMapper.login(student);
        return student;
    }

    @Override
    public Result changePassword(ChangePassword changePassword) {
        log.info("修改密码 --->>> 主键：{}，学号：{}，旧密码：{}，新密码：{}", changePassword.getId(),
                changePassword.getStudentID(),changePassword.getOldPassword(),changePassword.getNewPassword());
        Student student = new Student();
        student.setStudentID(changePassword.getStudentID());
        student.setPassword(changePassword.getOldPassword());
        Student checkStudentIDAndPassword = login(student);
        if (checkStudentIDAndPassword == null){
            return Result.error("用户名或者密码错误！");
        }

        loginMapper.changePassword(changePassword);
        return Result.success();
    }

    @Override
    @Transactional(
            rollbackFor = Exception.class,
            propagation = Propagation.REQUIRES_NEW)
    public Result registryStudentID(Student student) {

        Student checkStudentIDIfExistFromTbStuXx2205 = loginMapper.checkStudentIDIfExistFromTbStuXx2205(student);
        if (checkStudentIDIfExistFromTbStuXx2205 != null){
            return Result.error("该用户已经存在！");
        }
        Student checkStudentIDIfExistFromTbStu2022 = loginMapper.registryStudentIDCheckStudentIDExistFromTbStu2022(student);
        if (checkStudentIDIfExistFromTbStu2022 == null ){
            return Result.error("该生在荆州职业技术学院2022级，不存在！");
        }
        student.setUpdateTime(LocalDateTime.now());
        student.setCreateTime(LocalDateTime.now());

        loginMapper.registryStudentID(student);

        //  给学生从tb_stu2022表中添加默认信息
        registryStudentIDAfterInsertDefaultInfo(student);
        return Result.success();
    }

    private void registryStudentIDAfterInsertDefaultInfo(Student student) {

        /**
         * 该方法用于添加默认信息
         * 从 tb_stu2022表中向  tb_stu_xx2205表中插入默认数据
         */
        loginMapper.registryStudentIDAfterInsertDefaultInfo(student);
    }
}
